#include "Common.h"
#include "EventLoop.h"
#include "TcpServer.h"
// #include "Acceptor.h"

char rot13_char(char c) {
    if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
        return c + 13;
    else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
        return c - 13;
    else
        return c;
}


int onConnectionCompleted(const TcpConnectionPtr &conn) {
    printf("connection completed\n");
    return 0;
}

//数据读到buffer之后的callback
int onMessage(Buffer *input, const TcpConnectionPtr &conn) {

    if (conn.get()) {
        printf("get message from tcp connection %s\n", conn->name.c_str());
        printf("%s", input->getData());

        Buffer *output = new Buffer();
        int size = input->getReadableSize();
        for (int i = 0; i < size; i++) {
            output->doAppendChar(rot13_char(input->doReadChar()));
        }
        conn->sendBuffer(output);

    } else {
        printf("conn is nullptr\n");
    }
    return 0;
}

//数据通过buffer写完之后的callback
int onWriteCompleted(const TcpConnectionPtr &conn) {
    printf("write completed\n");
    return 0;
}

//连接关闭之后的callback
int onConnectionClosed(const TcpConnectionPtr &conn) {
    printf("connection closed\n");
    return 0;
}

// int onConnectionCompleted(TcpConnection *conn) {
//     printf("connection completed\n");
//     return 0;
// }

// int onMessage(Buffer *input, TcpConnection *conn) {
//     printf("get message from tcp connection %s\n", conn->name);
//     printf("%s", input->getData());

//     Buffer *output = new Buffer();
//     int size = input->getReadableSize();
//     for (int i = 0; i < size; i++) {
//     	output->doAppendChar(rot13_char(input->doReadChar()));
//     }
//     // printf("output data is  %s\n", output->data_);
//     // conn->sendBuffer(output);
//     // conn->sendBuffer(input);
//     return 0;
// }


// int onWriteCompleted(TcpConnection *conn) {
//     printf("write completed\n");
//     return 0;
// }

// int onConnectionClosed(TcpConnection *conn) {
//     printf("connection closed\n");
//     return 0;
// }




int main() {

	EventLoop main_loop;
	Acceptor acceptor(15556);

	TcpServer server(&main_loop, &acceptor, 0);

	server.setConnCompleteCallBack(onConnectionCompleted);
	server.setConnCloseCallBack(onConnectionClosed);
	server.setMessageCallBack(onMessage);
	server.setWriteCompleteCallBack(onWriteCompleted);

	server.start();
	main_loop.run();	
}